<template>
  <el-container>
    <div aria-label="A complete example of page header" class="page-header">
      <el-page-header @back="onBack">
        <template #content>
          <div class="flex items-center">
            <b class="text-large font-600 mr-3"> {{ articleDetailInfo.articleInfo.title }} </b>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center">
            <el-button type="success" @click="handleSupport">
              <span v-if="hasSupported">已点赞</span>
              <span v-else>点赞</span>
              <el-icon>
                <Pointer />
              </el-icon>
            </el-button>
            <el-button type="warning" @click="handleCollect">
              <span v-if="hasCollectd">已收藏</span>
              <span v-else>收藏</span>
              <el-icon>
                <Star />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="openComment">
              <el-icon>
                <ChatLineRound />
              </el-icon>
              <span>评论({{ articleDetailInfo.commentTotal }})</span>
            </el-button>
          </div>
        </template>
        <el-descriptions :column="4" size="small" class="mt-4">
          <el-descriptions-item label="浏览量：">
            {{ articleDetailInfo.articleInfo.viewer.length }}
          </el-descriptions-item>
          <el-descriptions-item label="收藏量：">
            {{ articleDetailInfo.articleInfo.beCollected.length }}
          </el-descriptions-item>
          <el-descriptions-item label="点赞量：">
            {{ articleDetailInfo.articleInfo.liker.length }}
          </el-descriptions-item>
          <el-descriptions-item label="作者：">
            <el-popover placement="top">
              <template #reference>
                <el-button type="primary" link>{{ articleDetailInfo.articleInfo.author }}</el-button>
              </template>
              <template #default>
                <div class="demo-rich-conent"
                  style="display: flex; gap: 14px; flex-direction: column;align-items: center;">
                  <el-avatar :size="60" :src="articleDetailInfo.articleInfo.userAccount.avatar || logo"
                    style="margin-bottom: 8px" />
                  <span>作者：{{ articleDetailInfo.articleInfo.author }}</span>
                  <span>粉丝数：{{ articleDetailInfo.articleInfo.userAccount.follower.length }}</span>
                  <el-button type="danger" v-if="hasAttention"
                    @click="handleFollow(articleDetailInfo.articleInfo.userAccount.uuid)">已关注</el-button>
                  <el-button type="info" v-else
                    @click="handleFollow(articleDetailInfo.articleInfo.userAccount.uuid)">关注</el-button>
                </div>
              </template>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="邮箱：">{{ articleDetailInfo.articleInfo.userAccount.email }}
          </el-descriptions-item>
          <el-descriptions-item label="文章类别：">{{ articleDetailInfo.articleInfo.category }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间：">
            {{ dayForMat(articleDetailInfo.articleInfo.createTime, 'YYYY/MM/DD') }}
          </el-descriptions-item>
          <el-descriptions-item label="状态：">
            {{ articleDetailInfo.articleInfo.publish_status }}
          </el-descriptions-item>
          <el-descriptions-item label="权限：">
            {{ articleDetailInfo.articleInfo.right }}
          </el-descriptions-item>
          <el-descriptions-item label="简介：">
            {{ articleDetailInfo.articleInfo.introduction }}
          </el-descriptions-item>
          <el-descriptions-item label="标签：">
            <el-tag v-for="tag in articleDetailInfo.articleInfo.tags" class="tag">{{ tag.name }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <hr>
        <b>
          <p class="mt-4 text-sm content" v-html="articleDetailInfo.articleInfo.content">
          </p>
        </b>
      </el-page-header>
    </div>
  </el-container>

  <el-drawer v-model="commnetVisavle" title="评论" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">评论({{ articleDetailInfo.commentTotal }})</h4>
      <el-button type="danger" @click="close">
        <el-icon class="el-icon--left">
          <CircleCloseFilled />
        </el-icon>
        关闭
      </el-button>
    </template>
    <div class="comment-container">
      <div class="comment-textarea">
        <el-avatar :size="40" :src="userInfoStore.userInfo.avatar || logo" class="avatar" />
        <div style="width: 100%;">
          <el-input type="textarea" placeholder="请输入评论" ref="iptRef" :rows="6" maxlength="1000"
            v-model="content"></el-input>
          <div class="content-bottom">
            <span>还能输入<b style="color:orange">{{ 1000 - content.length }}</b>个字符</span>
            <div style="padding: 10px;">
              <el-button round type="warning" size="small" @click="handleComment">评论</el-button>
            </div>
          </div>
        </div>
      </div>
      <Comment v-for="item in articleDetailInfo.comment" :comment="item" :key="item.id" @handle-reply="handleReply"
        @handle-del="handleDelComment" @handle-favor="handleFavor">
      </Comment>
      <!---->
    </div>
  </el-drawer>
</template>

<script setup lang='ts' name = "article_detail">
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import logo from '@/assets/images/logo.jpg'
import { useRoute, useRouter } from 'vue-router';
import { findOneArticle, collectionArticle, supportArticle, followUp, addArticleComment, delArticleComment, findArticleComment, commentFavor } from '@/api'
import { useUserInfoStore } from '@/stores';
import { View, Star, Pointer, ChatLineRound, CircleCloseFilled } from '@element-plus/icons-vue';
import { ElMessage, ElButton, ElDrawer, ElInput } from 'element-plus';
import { dayForMat } from '@/utils';
import Comment from '@/components/comment/index.vue'
const userInfoStore = useUserInfoStore()
const route = useRoute()
const router = useRouter()
const { uuid } = userInfoStore.userInfo

interface ArticleComment {
  author: string,
  content: string,
  createTime: string,
  id: number,
  userAccount: {
    uuid: string,
    avatar: string,
    nickname: string
  },
  parent?: ArticleComment,
  replies: Array<ArticleComment>
}

const commnetVisavle = ref<boolean>(false)
const content = ref('')
const iptRef = ref<any>()
const articleDetailInfo = reactive({
  articleInfo: {
    author: '',
    title: '',
    category: '',
    createTime: '',
    publish_status: '',
    right: '',
    views: '',
    content: '',
    introduction: '',
    viewer: [],
    beCollected: [],
    liker: [],
    userAccount: {
      avatar: logo,
      email: '',
      follower: [{ uuid: '' }],
      uuid: ''
    },
    tags: [{ name: '' }]
    ,
  },
  comment: [
    {
      author: '',
      content: '',
      createTime: '',
      userAccount: {
        avatar: '',
        nickname: '',
        uuid: ''
      },
      likers: [],
      id: 0,
      replies: [
        {
          author: '',
          content: '',
          createTime: '',
          userAccount: {
            avatar: '',
            nickname: '',
            uuid: ''
          },
          id: 0,
          likers: [],
        }
      ]
    }
  ],
  commentTotal: 0

})
onMounted(async () => {
  initArticle()
  initArticleComment()
})
const onBack = () => {
  router.back()
}



const initArticle = async () => {
  try {
    const res = await findOneArticle(+route.params.id, uuid)
    articleDetailInfo.articleInfo = res.data.data

  } catch (error) {
  }
}

const initArticleComment = async () => {
  try {
    const res = await findArticleComment({ articleId: +route.params.id })
    articleDetailInfo.comment = res.data.data
    articleDetailInfo.commentTotal = res.data.total

  } catch (error) {

  }
}

const handleCollect = async () => {
  try {
    const res = await collectionArticle({ uuid, articleId: +route.params.id })
    initArticle()
    ElMessage({
      type: 'success',
      message: res.data.msg
    })
  } catch (error) {
    ElMessage({
      type: 'success',
      message: '错误'
    })
  }
}

const handleSupport = async () => {
  try {
    const res = await supportArticle({ uuid, articleId: +route.params.id })
    ElMessage({
      type: 'success',
      message: res.data.msg
    })
    initArticle()
  } catch (error) {
    ElMessage({
      type: 'success',
      message: '错误'
    })
  }
}

const handleFollow = async (follow_uuid: string) => {
  const data = { uuid, follow_uuid }
  const res = await followUp(data)
  if (res.data.code == 200) {
    ElMessage({
      message: res.data.msg,
      type: 'success'
    })
    initArticle()
  } else {
    ElMessage({
      type: 'error',
      message: res.data.msg
    })
  }
}

const handleComment = async () => {
  const data = { uuid, content: content.value, articleId: +route.params.id }
  if (content.value.trim() === '') {
    ElMessage({ type: 'error', message: '内容不能为空' })
    return nextTick(() => {
      iptRef.value?.focus()
    })
  }
  try {
    const res = await addArticleComment(data)
    setTimeout(async () => {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      initArticleComment()
      content.value = ''
    }, 1000)

  } catch (error) {
    ElMessage({
      message: '评论失败',
      type: 'error'
    })
  }
}

//接受回复信息
const handleReply = async (content: string, parentId: number) => {
  const data = { uuid, articleId: +route.params.id, content, parentId }
  try {
    const res = await addArticleComment(data)
    ElMessage({
      type: 'success',
      message: res.data.msg
    })
    initArticleComment()
  } catch (error) {

  }
}


const handleDelComment = async (commentId: number) => {
  const data = { uuid, articleId: +route.params.id, commentId }

  try {
    const res = await delArticleComment(data)

    ElMessage({
      type: 'success',
      message: res.data.msg
    })
    initArticleComment()
  } catch (error) {

  }

}

const handleFavor = async (commentId: number) => {
  const data = { uuid, articleId: +route.params.id, commentId }
  try {
    const res = await commentFavor(data)
    ElMessage({
      type: 'success',
      message: res.data.msg
    })
    initArticleComment()
  } catch (error) {

  }
}

const hasCollectd = computed(() => {
  return articleDetailInfo.articleInfo.beCollected.findIndex((item: { uuid: string }) => item.uuid === uuid) !== -1
})

const hasSupported = computed(() => {
  return articleDetailInfo.articleInfo.liker.findIndex((item: { uuid: string }) => item.uuid === uuid) !== -1
})

const hasAttention = computed(() => {
  return articleDetailInfo.articleInfo.userAccount.follower.findIndex((item: { uuid: string }) => item.uuid === uuid) !== -1
})

//打开评论
const openComment = async () => {
  commnetVisavle.value = true
  nextTick(() => {
    setTimeout(() => {
      iptRef.value?.focus()
    }, 50)
  })
}


</script>
<style scoped lang="scss">
.common-layout {
  height: 100%;

  .page-header {
    width: 100%;
  }

  .tag {
    margin-right: 10px;
  }
}


.comment-container {
  .comment-textarea {
    display: flex;
    border-bottom: 1px solid #ccc;

    .avatar {
      margin-right: 8px
    }

    .content-bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

  }

  .reply-box {
    display: flex;
    padding: 10px 0;
    margin: 10px 0;

    .avatar {
      margin-right: 8px
    }
  }

}
</style>